package com.shortlink.server.mq;

import cn.hutool.json.JSONUtil;
import com.shortlink.server.dao.entity.ShortLinkIpStatsDO;
import com.shortlink.server.dao.entity.ShortLinkStatsRecordDO;
import com.shortlink.server.remote.ApiRemoteService;
import com.shortlink.server.service.ShortLinkIpStatsService;
import com.shortlink.server.service.ShortLinkStatsRecordService;
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import static com.shortlink.common.constant.MQConstant.*;

/**
 * 短链接监控消费者
 *
 * @author wp
 */
@Component
@RequiredArgsConstructor
@RocketMQMessageListener(topic = SHORT_LINK_STATS_TOPIC, selectorExpression = STATS_SAVE_TAG, consumerGroup = MQ_CONSUMER_GROUP)
public class ShortLinkStatsSaveConsumer implements RocketMQListener<String> {
    private final ShortLinkStatsRecordService shortLinkStatsRecordService;
    private final ShortLinkIpStatsService shortLinkIpStatsService;
    private final ApiRemoteService apiRemoteService;

    @Override
    @Transactional
    public void onMessage(String shortLinkStatsRecordStr) {
        ShortLinkStatsRecordDO shortLinkStatsRecord = JSONUtil.toBean(shortLinkStatsRecordStr, ShortLinkStatsRecordDO.class);
        ShortLinkIpStatsDO shortLinkIpStats = new ShortLinkIpStatsDO();
        shortLinkIpStats.setDomain(shortLinkStatsRecord.getDomain());
        shortLinkIpStats.setShortUri(shortLinkStatsRecord.getShortUri());
        shortLinkIpStats.setIp(shortLinkStatsRecord.getIp());
        try {
            System.out.println(shortLinkIpStats);
            shortLinkIpStatsService.save(shortLinkIpStats);
            shortLinkStatsRecord.setIpType(0);
        } catch (DuplicateKeyException e) {
            shortLinkStatsRecord.setIpType(1);
        }

        shortLinkStatsRecord.setLocale(apiRemoteService.getIpLocale(shortLinkStatsRecord.getIp()));

        shortLinkStatsRecordService.save(shortLinkStatsRecord);
    }
}
